package com.qyhl.module_activities.act.comment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.act.ActCommentBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

public class CommentListFragment extends BaseFragment implements CommentListContract.CommentListView {
    @BindView(R2.id.act_comments_list_rec)
    RecyclerView mCommentsList;
    @BindView(R2.id.act_comment_refresh)
    SmartRefreshLayout mCommentRefresh;
    @BindView(R2.id.act_comment_loading)
    LoadingLayout mCommentLoading;

    /**
     * 活动Id
     */
    private int mActId;
    /**
     * 控制器
     */
    private CommentListPresenter mPresenter;

    /**
     * 最后一条ID
     */
    private int mLastId;
    /**
     * 评论数据
     */
    private List<ActCommentBean> mCommentListData = new ArrayList<>();
    /**
     * 适配器
     */
    private CommonAdapter<ActCommentBean> mCommentAdapter;

    //发送的评论内容
    private String commentText;

    public static CommentListFragment newInstance(int actId) {
        CommentListFragment fragment = new CommentListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("actId", actId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_fragment_comment_list, container, false);
    }

    @Override
    protected void create() {
        mActId = getArguments().getInt("actId");
        mPresenter = new CommentListPresenter(this);
        BusFactory.getBus().register(this);
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        mCommentLoading.setStatus(LoadingLayout.Loading);
        mPresenter.getComment(mActId, 0);

        mCommentLoading.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mCommentLoading.setStatus(LoadingLayout.Loading);
                mPresenter.getComment(mActId, 0);
            }
        });

        mCommentRefresh.setEnableLoadMore(true);
        mCommentRefresh.setEnableRefresh(false);
        mCommentRefresh.setDisableContentWhenRefresh(true);
        mCommentRefresh.setRefreshFooter(new ClassicsFooter(getContext()));
        mCommentRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getComment(mActId, mLastId);
            }
        });

        mCommentsList.setLayoutManager(new LinearLayoutManager(getContext()));
        mCommentsList.setAdapter(mCommentAdapter = new CommonAdapter<ActCommentBean>(getContext(), R.layout.act_item_act_comment, mCommentListData) {
            @Override
            protected void convert(ViewHolder holder, ActCommentBean actCommentBean, int position) {
                if (getActivity() != null && !getActivity().isFinishing()) {
                    if (position == mCommentListData.size() - 1) {
                        holder.setVisible(R.id.fengexian, false);
                    } else {
                        holder.setVisible(R.id.fengexian, true);
                    }
                    Glide.with(mContext)
                            .load(actCommentBean.getCommenterAvatar())
                            .apply(new RequestOptions().transform(new GlideCircleTransform(mContext)).error(R.drawable.comment_head_default))
                            .into((ImageView) holder.getView(R.id.comment_avatar));
                    holder.setText(R.id.comment_user, actCommentBean.getCommenterNickName());
                    holder.setText(R.id.comment_content, actCommentBean.getContent());
                    holder.setText(R.id.comment_time, actCommentBean.getCommentTime());
                }
            }
        });
    }

    @Override
    protected void onVisible() {
        mCommentLoading.setStatus(LoadingLayout.Loading);
        mPresenter.getComment(mActId, 0);
    }

    @Override
    protected void onHide() {

    }

    @Override
    public void onDestroy() {
        BusFactory.getBus().unregister(this);
        super.onDestroy();
    }

    @Override
    public void commentError(String msg) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            Toasty.normal(getContext(), msg).show();
        }
    }

    @Override
    public void getCommentError(String msg, boolean isHead) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            mCommentRefresh.finishRefresh();
            mCommentRefresh.finishLoadMore();
            if (isHead) {
                mCommentLoading.setErrorText(msg);
                mCommentLoading.setReloadButtonText("点击重试");
                mCommentLoading.setErrorImage(R.drawable.error_content);
                mCommentLoading.setStatus(LoadingLayout.Error);
            } else {
                Toasty.normal(getContext(), msg).show();
            }
        }
    }

    @Override
    public void onSuccess(List<ActCommentBean> data, boolean isHead) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            mCommentRefresh.finishRefresh();
            mCommentRefresh.finishLoadMore();
            mCommentLoading.setStatus(LoadingLayout.Success);
            if (isHead) {
                mCommentListData.clear();
                mCommentListData.addAll(data);
            } else {
                mCommentListData.addAll(data);
            }
            mCommentAdapter.notifyDataSetChanged();
            mLastId = mCommentListData.get(mCommentListData.size() - 1).getId();
        }
    }

    @Override
    public void commentSuccess(boolean isshow, String msg) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            if (isshow) {
                //评论先发后审
//                ActCommentBean bean = new ActCommentBean();
//                bean.setCommentTime("刚刚");
//                bean.setContent(commentText);
//                bean.setCommenterNickName(MyConfig.nickName);
//                bean.setCommenterAvatar(MyConfig.headicon);
//                mCommentListData.add(0, bean);
//                mCommentAdapter.notifyDataSetChanged();

                mPresenter.getComment(mActId, 0);
            }
            Toasty.normal(getContext(), msg).show();
        }
    }

    @Override
    public void onEmpty(boolean isHead) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            if (isHead) {
                mCommentLoading.setErrorText("暂无评论");
                mCommentLoading.setReloadButtonText("点击刷新");
                mCommentLoading.setErrorImage(R.drawable.error_content);
                mCommentLoading.setStatus(LoadingLayout.Error);
            } else {
                mCommentRefresh.finishRefresh();
                mCommentRefresh.finishLoadMore();
            }
        }
    }

    /**
     * 发送评论
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendComment(final Event.ActivityEvent event) {
        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    commentText = event.getText();
                    mPresenter.sendComment(mActId, commentText);
                } else {
                    Toasty.normal(getActivity(), "尚未登录或登录已失效").show();
                    RouterManager.routerLogin(getActivity(), 0);
                }
            }

            @Override
            public void error(String s) {

            }
        });

    }
}
